#include "listwidget.h"
#include "ui_listwidget.h"

ListWidget::ListWidget(QWidget *parent) :
    QWidget(parent),
    currentLabel(NULL),
    currentLineEdit(NULL),
    index(0),
    ui(new Ui::ListWidget)
{
    ui->setupUi(this);
}

ListWidget::~ListWidget()
{
    delete ui;
}

void ListWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
    // 检测鼠标双击的位置
    QWidget* widget = childAt(event->pos());
    QLabel* label = qobject_cast<QLabel*>(widget);
    if (label)
    {
        if(ui->chineseNameLabel->text() == label->text()) index = 0;
        else if(ui->signalLabel->text() == label->text()) index = 1 ;
        else if(ui->funcLabel->text() == label->text()) index = 2;
        else
        {
            index = 3;
            //这里不允许修改硬件连接
            qDebug() << "can not modify hardware connect";
            return;
        }

        // 如果双击的是 QLabel，显示 QLineEdit
        QLineEdit* lineEdit = new QLineEdit(label->text(), this);
        lineEdit->resize(label->size());
        lineEdit->move(label->pos());
        lineEdit->show();
        lineEdit->setFocus();

        // 保存当前 QLabel 和 QLineEdit
        currentLabel = label;
        currentLineEdit = lineEdit;

        // 连接信号和槽，处理输入完成
        connect(lineEdit,SIGNAL(editingFinished()),this,SLOT(updateLabel()));
    }
}

void ListWidget::setChineseNameLabel(const QString &name)
{
    ui->chineseNameLabel->setText(name);
}

void ListWidget::setFuncLabel(const QString &funcStr)
{
    ui->funcLabel->setText(funcStr);
}

void ListWidget::setSignalLabel(const QString &signalLabel)
{
    ui->signalLabel->setText(signalLabel);
}

void ListWidget::setHardwareConnectLabel(const QString &label)
{
    ui->hardwareConnectLabel->setText(label);
}

void ListWidget::setListWidgetData(const IOData* data)
{
    setChineseNameLabel(data->_pinName);
    setFuncLabel(data->_functionConnect);
    setSignalLabel(data->_signal);
    setHardwareConnectLabel(data->_hardwareConnect);
}

QString ListWidget::getChineseNameLabel()
{
    return ui->chineseNameLabel->text();
}

QString ListWidget::getFuncLabel()
{
    return ui->funcLabel->text();
}

QString ListWidget::getSignalLabel()
{
    return ui->signalLabel->text();
}

QString ListWidget::getHardwareConnectLabel()
{
    return ui->hardwareConnectLabel->text();
}

//用于更新用户修改完对应控件的内容
void ListWidget::updateLabel()
{
    // 获取 QLineEdit 的内容并更新 QLabel
    if (currentLabel && currentLineEdit) {
        currentLabel->setText(currentLineEdit->text());
        currentLineEdit->deleteLater();
        //这里通过信号的方式发送给主界面，让主界面对对应的数据中的内容进行修改
        QString sendLabel = QString::number(index) + currentLabel->text();
        emit labelTextChanged(sendLabel,ui->hardwareConnectLabel->text());
        currentLabel = NULL;
        currentLineEdit = NULL;
        index = 0;
    }
}
